% script generating ERP movie for all subjects of the nondual experiment
% Arnaud Delorme - Feb 17th, 2010

baseline = [-2000 -1000];
conditions = [1 3]; %1=audio; 2=blank; 3=light

% load study
% ----------
eeglab
[STUDY ALLEEG]  = pop_loadstudy('filename', 'nondual27subjects.study', 'filepath', pwd);
[STUDY, ALLEEG] = std_checkset(STUDY, ALLEEG);
CURRENTSTUDY    = 1; EEG = ALLEEG; CURRENTSET = [1:length(EEG)];
[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, {}, 'allcomps', 'on', 'recompute', 'on', 'erp', 'on', 'erpparams', { 'rmbase', baseline 'savetrials' 'on' });

% make movie for single subject
% get all subjects data
% ----------------
ff = {'elaine' ; 'edmay' ; 'bryan' ; 'randy' ; 'gene' ; 'hoss' ; 'gordon' ; 'joe' ; 'curt'; 'johnny'; 'sherri'; ...
      'richard'; 'judy' ; 'johnastin' ; 'john'; 'federico' ; 'steve' ; 'christer' ; 'carol' ; 'francis' ; 'swamisita' ; ...
      'yogafarm'; 'loch' ; 'gary' ; 'zoran' ; 'james'; 'arno' };

for subject = 1:length(ff)
    [STUDY alldata alltimes] = std_readerp(STUDY,ALLEEG,'channels', { ALLEEG(1).chanlocs.labels }, 'timerange', [-500 500], 'singletrials', 'on', 'subject', ff{subject});

    % compute statistics and plot new movie
    % -------------------------------------
    [pcond] = std_stat(alldata(conditions), 'condstats', 'on', 'statistics', 'param', 'naccu', 200); %, 'threshold', threshold);
    clear M tmpdata;
    latencies = STUDY.changrp(1).erptimes;
    chans = 1:ALLEEG(1).nbchan; chans(21:22) = [];
    for index = 1:length(latencies)
        tmppcond{1} = squeeze(pcond{1}(index,:));
        for c = 1:length(conditions)
            tmpdata{c}  = squeeze(mean(alldata{conditions(c)}(index,:,:),3));
        end;
        textstr = sprintf('%2.0f ms                                                     ', latencies(index));
        std_chantopo(tmpdata', 'datatype', 'erp', 'unitx', '\muV', 'binarypval', 'off', 'condstats', tmppcond, ...
                               'chanlocs', ALLEEG(1).chanlocs(chans), 'ylim', [-3 3], 'titles', { STUDY.condition{conditions} 'p-value' }')
        %delete(gca)
        textsc(textstr, 'title');
        drawnow;
        M(index) = getframe(gcf);
        close;
    end;
    movie2avi(M, sprintf('erpmovie_%s.avi', ff{subject}), 'fps', 5);

end;
